package com.zhs.gccs.service;

import android.app.IntentService;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhs.gccs.dao.TaskGccsFileDao;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.BackgroudObserver;
import com.zhs.gccs.http.CommonCallback;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.http.RequestBodyUpload;
import com.zhs.gccs.listener.FileUploadListener;
import com.zhs.gccs.listener.GccsDataSaveListener;
import com.zhs.gccs.model.GccsTaskFile;
import com.zhs.gccs.vo.BaseBean;
import com.zhs.gccs.vo.UploadSuccessBean;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UploadFileService extends IntentService {
    private TaskGccsFileDao taskGccsFileDao;

    public UploadFileService() {
        this("UploadFileService");
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public UploadFileService(String name) {
        super(name);
        taskGccsFileDao = new TaskGccsFileDao();
    }



    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        uploadGcccFileSlient();
                        Thread.sleep(5000);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //Log.e("UploadFileService",e);
                    }
                }
            }
        }).start();
    }


    public RequestBody createRequestBody(Map<String, Object> paramMap){
        return FormBody.create(new Gson().toJson(paramMap),
                MediaType.parse("application/json; charset=utf-8"));
    }

    public void toSubscribeSingleOb(Observable<String> ob, BackgroudObserver observer) {
        ob.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private synchronized void uploadGcccFileSlient() {
        //v_file_upload_tips.
        List<GccsTaskFile> caFiles = taskGccsFileDao.
                findNeedSyncList();
        if (caFiles == null || caFiles.size() == 0) {
            return;
        }
        GccsTaskFile file = caFiles.get(0);
        if (TextUtils.isEmpty(file.getLocalUrl())) {
            return;
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("pid", file.getPid());
        List<String> loaclFilePaths = new ArrayList<>();
        if ("0".equals(file.getFileType())) {
            loaclFilePaths.add(file.getLocalUrl());
        } else if ("2".equals(file.getFileType())) {//视频
            loaclFilePaths.add(file.getLocalUrl());
            //缩略图
            if (file.getVideoThumbLocalUrl() != null) {
                loaclFilePaths.add(file.getVideoThumbLocalUrl());
            }
        }
        toUploadGcccFiles(loaclFilePaths, params, new FileUploadListener() {
            @Override
            public void onSuccess(String data) {
                Type type = TypeToken.getParameterized(BaseBean.class, GccsTaskFile.class).getType();
                BaseBean<GccsTaskFile> bean = new Gson().fromJson(data, type);
                if (bean != null && bean.getCode() == 200) {
                    GccsTaskFile finalCjFile = bean.getData();
                    file.setFilePath(finalCjFile.getFilePath());
                    file.setBucket(finalCjFile.getBucket());
                    file.setObjectName(finalCjFile.getObjectName());
                    file.setFileName(finalCjFile.getFileName());
                    file.setUniqueName(finalCjFile.getUniqueName());
                    file.setFileSize(finalCjFile.getFileSize());
                    file.setFileExt(finalCjFile.getFileExt());

                    saveGccsDataFile(file, new GccsDataSaveListener() {
                        @Override
                        public void onSuccess(String result) {
                            Type type = TypeToken.getParameterized(BaseBean.class, UploadSuccessBean.class).getType();
                            BaseBean<UploadSuccessBean> bean = new Gson().fromJson(result, type);
                            if (bean != null && bean.getData() != null) {
//                                file.setSync(true);
//                                file.setId(bean.getData().getid() + "");//服务器文件id
//                                taskGccsFileDao.addOrUpdate(file);
                                taskGccsFileDao.deleteByLocalId(file.getLocalId());
                                //uploadGcccFileSlient();
                            }
                        }

                        @Override
                        public void onError() {
                            //uploadGcccFileSlient();
                        }
                    });
                }
            }

            @Override
            public void onError() {

            }
        });
    }

    private void toUploadGcccFiles(List<String> loaclFilePaths,
                                   HashMap<String, String> params,
                                   FileUploadListener listener) {
        String contentType = "multipart/form-data";
        List<MultipartBody.Part> parts = new ArrayList<>();
        for (String filePath : loaclFilePaths) {
            File file = new File(filePath);
            RequestBody requestFile = RequestBody.create(MediaType.parse(contentType), file);
            RequestBodyUpload requestBodyUpload = new RequestBodyUpload(requestFile, file.getName(), new CommonCallback.OnProgressWithNameCallBack() {
                @Override
                public void onProgress(String filename, float percent) {
                    Log.e("xp", "filename = " + filename + ", percent = " + percent);
                }
            });
            MultipartBody.Part filePartBody = MultipartBody.Part.
                    createFormData("file", file.getName(), requestBodyUpload);
            parts.add(filePartBody);
        }
        //构造参数
        Map<String, RequestBody> _params = new HashMap<>();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            RequestBody requestBody = RequestBody.
                    create(MediaType.parse(contentType),
                            entry.getValue());
            _params.put(entry.getKey(), requestBody);
        }
        toSubscribeSingleOb(Api.getDefault()
                        .gccsUploadFile(_params, parts), new BackgroudObserver(getApplication()) {
                    @Override
                    protected void _onNext(String result) {
                        Log.e("CZF", "gccsUploadFile：" + result);
                        listener.onSuccess(result);
                    }

                    @Override
                    protected void _onError(String result) {
                        Log.e("CZF", "gccsUploadFile：" + result);
                        listener.onError();
                    }
                });
    }
    private void saveGccsDataFile(GccsTaskFile file, GccsDataSaveListener listener) {
        Map hashMap = JSON.parseObject(JSON.toJSONString(file));
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault()
                        .saveGccsFile(requestBody),
                new BackgroudObserver(getApplication()) {
                    @Override
                    protected void _onNext(String result) {
                        if (listener != null) listener.onSuccess(result);
                    }

                    @Override
                    protected void _onError(String result) {
                        if (listener != null) listener.onError();
                    }
                });
    }
}
